package com.qiniuyun.pictransmission.service.impl;

import com.qiniuyun.pictransmission.config.QiNiuYunConfig;
import com.qiniuyun.pictransmission.service.DownloadService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.qiniu.util.Auth;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.*;


@Service
public class DownloadServiceImpl implements DownloadService {

    @Autowired
    QiNiuYunConfig qiNiuYunConfig;

    @Override
    public String download(String picName) {
        //获取downloadUrl
        String downloadUrl = getDownloadUrl("http://rekq92rme.hn-bkt.clouddn.com/"+picName);
        //本地保存路径
        String filePath = "D:/";
        String targetUrl = download(downloadUrl, filePath);
        if(targetUrl == null){
            return "下载失败";
        }else {
            return targetUrl;
        }
    }

    /**
     * 获取下载文件路径，即：donwloadUrl
     * @return
     */
    public String getDownloadUrl(String targetUrl) {
        long expireInSeconds = 60;//自定义链接过期时间
        Auth auth = Auth.create(qiNiuYunConfig.getAccessKey(), qiNiuYunConfig.getSecretKey()); //密钥配置
        return auth.privateDownloadUrl(targetUrl,expireInSeconds);
    }

    /**
     * 通过发送http get 请求获取文件资源
     * @param url
     * @param filepath
     * @return
     */
    private static String download(String url, String filepath) {
        OkHttpClient client = new OkHttpClient();
        System.out.println("下载链接为："+url);
        Request req = new Request.Builder().url(url).build();
        Response resp = null;
        String targetUrl = null;
        try {
            resp = client.newCall(req).execute();
            System.out.println(resp.isSuccessful());
            if(resp.isSuccessful()) {
                targetUrl = url;
                return targetUrl;
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Unexpected code " + resp);
        }
        return targetUrl;
    }


    /**
     * 读取字节输入流内容
     * @param is
     * @return
     */
    private static byte[] readInputStream(InputStream is) {
        ByteArrayOutputStream writer = new ByteArrayOutputStream();
        byte[] buff = new byte[1024 * 2];
        int len = 0;
        try {
            while((len = is.read(buff)) != -1) {
                writer.write(buff, 0, len);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return writer.toByteArray();
    }
}
